import { message } from "@/utils/message";
import { queryAppModuleList, deleteAppModule } from "@/api/syschat";
import { type PaginationProps } from "@pureadmin/table";
import { reactive, ref, computed, onMounted } from "vue";

export function useAppModule() {
  const INITIAL_DATA = {
    id: "",
    manageid: "",
    platform: "1",
    name: "",
    tag: "Android iOS",
    image: "https://api.tyousan.top/upload/modules/20230827095415.png",
    content: "",
    price: "0",
    count: "999",
    orderby: "0",
    addtime: "",
    mdurl: "",
    updatetime: ""
  };

  const searchForm = reactive({
    platform: "1",
    name: ""
  });
  const dialogVisible = ref(false);
  const formData = ref({ ...INITIAL_DATA });

  const dataList = ref([]);
  const loading = ref(true);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });

  const columns: TableColumnList = [
    {
      type: "selection",
      width: 55,
      align: "left",
      hide: ({ checkList }) => !checkList.includes("勾选列")
    },
    {
      label: "序号",
      type: "index",
      width: 70,
      hide: ({ checkList }) => !checkList.includes("序号列")
    },
    {
      label: "编号",
      prop: "id",
      minWidth: 130
    },
    {
      label: "平台",
      prop: "platform",
      minWidth: 130,
      formatter: row => {
        switch (row.platform) {
          case 1:
            return "用友";
          case 2:
            return "uni-app";
        }
      }
    },
    {
      label: "插件名称",
      prop: "name",
      minWidth: 90,
      cellRenderer: ({ row }) => (
        <el-popover
          effect="light"
          trigger="hover"
          placement="right"
          width="auto"
        >
          {{
            default: () => {
              return (
                <>
                  <div>
                    <img src={row.image} style="width: 125px; height: 89px" />
                  </div>
                </>
              );
            },
            reference: () => {
              return <el-tag>{row.name}</el-tag>;
            }
          }}
        </el-popover>
      )
    },
    {
      label: "标签",
      prop: "tag",
      minWidth: 90
    },
    {
      label: "描述",
      prop: "content",
      minWidth: 90,
      cellRenderer: ({ row }) => (
        <el-popover
          effect="light"
          trigger="hover"
          placement="right"
          width="300"
        >
          {{
            default: () => {
              return (
                <>
                  <div>{row.content}</div>
                </>
              );
            },
            reference: () => {
              const size = row.content.length;
              let result = row.content;
              if (size > 20) {
                result = row.content.slice(0, 20);
              } else {
                result = row.content;
              }
              return <el-tag>{result}</el-tag>;
            }
          }}
        </el-popover>
      )
    },
    {
      label: "更新时间",
      minWidth: 90,
      prop: "updatetime"
    },
    {
      label: "排序",
      prop: "orderby",
      minWidth: 60
    },
    {
      label: "操作",
      fixed: "right",
      width: 180,
      slot: "operation"
    }
  ];
  const buttonClass = computed(() => {
    return [
      "!h-[20px]",
      "reset-margin",
      "!text-gray-500",
      "dark:!text-white",
      "dark:hover:!text-primary"
    ];
  });

  function handleAdd() {
    dialogVisible.value = true;
    formData.value = { ...INITIAL_DATA };
  }

  function handleUpdate(row) {
    // console.log(`current row: ${JSON.stringify(row)}`);
    dialogVisible.value = true;
    formData.value = {
      ...row,
      platform: row.platform == 1 ? "1" : "2"
    };
  }

  function handleDelete(row) {
    deleteAppModule(row)
      .then(res => {
        if (res.success) {
          message("删除成功", { type: "success" });
          onSearch();
        } else {
          message("删除数据异常:" + res.errMsg, { type: "error" });
        }
      })
      .catch(error => {
        message("删除数据异常:" + JSON.stringify(error), { type: "error" });
      });
  }

  function handleSizeChange(val: number) {
    console.log(`${val} items per page`);
  }

  function handleCurrentChange(val: number) {
    console.log(`current page: ${val}`);
    onSearch();
  }

  function handleSelectionChange(val) {
    console.log("handleSelectionChange", val);
  }

  async function onSearch() {
    loading.value = true;
    queryAppModuleList({
      name: searchForm.name,
      platform: searchForm.platform,
      pageSize: pagination.pageSize,
      currentPage: pagination.currentPage
    })
      .then(res => {
        // console.log(`current row: ${JSON.stringify(res)}`);
        if (res.success) {
          dataList.value = res.data.list;
          pagination.total = res.data.total;
          loading.value = false;
        } else {
          message("查询数据异常:" + res.errMsg, { type: "error" });
        }
      })
      .catch(error => {
        message("查询数据异常:" + JSON.stringify(error), { type: "error" });
      });
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  onMounted(() => {
    onSearch();
  });

  return {
    dialogVisible,
    formData,
    searchForm,
    loading,
    columns,
    dataList,
    pagination,
    buttonClass,
    onSearch,
    resetForm,
    handleAdd,
    handleUpdate,
    handleDelete,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange
  };
}
